﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MxWeiXinPF.Web.admin.sms
{
    public class BlueSmsMgr
    {
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        public static string BlanceUrl = ConfigurationManager.AppSettings["WebReference.Service.BalanceQueryUrl"];
        BLL.wx_sms_config scBll = new BLL.wx_sms_config();
        string ucode = "";
        string pwd = "";
        string qianming = "";
        int wid;

        public BlueSmsMgr(int wid)
        {
            this.wid = wid;
            Model.wx_sms_config smsConfig = scBll.GetWidModel(wid);
            if (smsConfig != null)
            {
                ucode = smsConfig.ucode;
                pwd = smsConfig.pwd;
                qianming = smsConfig.qianming;

            }
        }

        /// <summary>
        /// 短信发送需要发送的手机号码，多个号码以逗号分割 ,建议200一组提交
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public string SendSMS(string phone, string content)
        {
            return SendSMS(phone, content, "", "", 0);
        }

        /// <summary>
        /// 短信发送需要发送的手机号码，多个号码以逗号分割 ,建议200一组提交
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="content"></param>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public string SendSMS(string phone, string content, string moduleName)
        {
            return SendSMS(phone, content, moduleName, "", 0);
        }

        /// <summary>
        /// 短信发送需要发送的手机号码，多个号码以逗号分割 ,建议200一组提交
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="content">短信内容</param>
        /// <param name="moduleName">发送短信的模块名称</param>
        /// <param name="actionName">模块活动的名称</param>
        /// <param name="actionId">模块活动的主键id</param>
        /// <returns>需要发送的手机号码，多个号码以逗号分割 ,建议200一组提交</returns>
        public string SendSMS(string phone, string content, string moduleName, string actionName, int actionId)
        {
            BLL.wx_sms_info smsBll = new BLL.wx_sms_info();
            Model.wx_sms_info smsinfo = new Model.wx_sms_info();

            if (ucode == "" || pwd == "" || qianming == "")
            {
                return "失败：帐号、密码或者签名未填写";
            }
            //if (qianming.Contains("【") && qianming.Contains("】"))
            //{
            //    //签名必须包含“【”和“】”
            //}
            //else
            //{
            //    return "失败：签名填写错误";
            //}
            try
            {
                if (phone.Trim() == "")
                {
                    return "失败：手机号码为空";
                }
                if (content.Trim() == "")
                {
                    return "失败：短信内容为空";
                }


                string[] phoneArr = phone.Split(',');
                string ret = "";
                for (int i = 0; i < phoneArr.Length; i++)
                {
                    if (phoneArr[i].Trim() != "" && phoneArr[i].Trim().Length > 5)
                    {
                        ret = Send(ucode, pwd, phoneArr[i], content + " " + qianming);
                        //----- 记录日志 begin -----\\
                        smsinfo = new Model.wx_sms_info();
                        smsinfo.wid = wid;
                        smsinfo.createDate = DateTime.Now;
                        smsinfo.moduleName = moduleName;
                        smsinfo.actionName = actionName;
                        smsinfo.actionId = actionId;
                        smsinfo.tel = phoneArr[i];
                        smsinfo.smsContent = content + " " + qianming;
                        smsinfo.sStatusNum = ret;
                        smsinfo.sStatus = smsSendReturnValue(ret);
                        smsBll.Add(smsinfo);
                        //----- 记录日志 end -----\\
                    }
                }


                return (smsSendReturnValue(ret));
            }
            catch (Exception ex)
            {

                smsinfo = new Model.wx_sms_info();
                smsinfo.wid = wid;
                smsinfo.createDate = DateTime.Now;
                smsinfo.moduleName = moduleName;
                smsinfo.actionName = actionName;
                smsinfo.actionId = actionId;
                smsinfo.tel = phone;
                smsinfo.smsContent = content;
                smsinfo.sStatusNum = "失败：短信发送失败：" + ex.Message;
                smsinfo.sStatus = "发送失败，抛出异常信息";
                smsBll.Add(smsinfo);

                return "失败：短信发送失败：" + ex.Message;
            }


        }

        /// <summary>
        /// 查询余额
        /// </summary>
        /// <returns></returns>
        public string getBlance()
        {
            string ret = "";
            ret = GetBalance(ucode, pwd);
            if (!string.IsNullOrWhiteSpace(ret))
            {
                string[] strs = ret.Split(',');
                if (strs.Length == 2)
                {
                    return strs[1];
                }
            }
            return ret;
        }

        /// <summary>
        /// 短信发送返回的状态
        /// </summary>
        /// <param name="smsStatus"></param>
        /// <returns></returns>
        public string smsSendReturnValue(string smsStatus)
        {
            string ret = "";
            try
            {
                if (string.IsNullOrWhiteSpace(smsStatus))
                {
                    return "短信发送失败";
                }
                //smsStatus = smsStatus.Replace("\n", string.Empty).Replace("\r", string.Empty);
                string[] strs = smsStatus.Split('\n');
                string[] strs2 = strs[0].Split(',');
                if (strs2 == null || strs2.Length < 2)
                {
                    return "短信发送失败";
                }

                string status = strs2[1];
                switch (status)
                {

                    case "0":
                        ret = "成功";
                        break;
                    case "-1":
                        ret = "失败：帐号密码错误";
                        break;
                    case "-2":
                        ret = "失败：帐号被停用";
                        break;
                    case "-3":
                        ret = "失败：帐号类型不允许使用";
                        break;
                    case "-4":
                        ret = "失败：手机号码为空";
                        break;
                    case "-5":
                        ret = "失败：短信内容为空";
                        break;
                    case "-6":
                        ret = "失败：内容包含黑字典字样";
                        break;
                    case "-7":
                        ret = "失败：通道分配错误";
                        break;
                    case "-8":
                        ret = "失败：余额不足";
                        break;
                    case "-9":
                        ret = "失败：定时时间格式不正确 2012-07-27 08:30:00";
                        break;
                    default:
                        ret = "失败：短信发送异常";
                        break;



                }
            }
            catch (Exception ex)
            {
                ret = "失败：短信发送异常，" + ex.Message;
            }

            return ret;

        }

        private string Send(string account, string password, string mobile, string content)
        {
            string postStrTpl = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&product=&extno=";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;

            Stream newStream = myRequest.GetRequestStream();
            // Send the data.
            newStream.Write(postData, 0, postData.Length);
            newStream.Flush();
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                 return reader.ReadToEnd();
                //反序列化upfileMmsMsg.Text
                //实现自己的逻辑
            }
            else
            {
                //访问失败
                return "发送失败";
            }
        }

        private string GetBalance(string account,string password)
        {
            string postStrTpl = "account={0}&pswd={1}";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password));

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;

            Stream newStream = myRequest.GetRequestStream();
            // Send the data.
            newStream.Write(postData, 0, postData.Length);
            newStream.Flush();
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                return reader.ReadToEnd();
                //反序列化upfileMmsMsg.Text
                //实现自己的逻辑
            }
            else
            {
                //访问失败
                return "发送失败";
            }
        }
    }
}